package com.epam.utils;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import com.epam.DAO.CarDAO;
import com.epam.DAO.Factories.DAOFactory;
import com.epam.entity.Car;

public class CarConverter implements Converter {

	private DAOFactory daoFactory;
	private CarDAO carDAO;
	
	public CarConverter(){
		daoFactory = DAOFactory.getDAOFactory(DAOFactory.CURRENT_IMPLEMENTATION);
		carDAO = daoFactory.getCarDAO();
	}
	
	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String carId) {
		
		if (carId == null || carId.length() == 0)
			return null;
		return carDAO.read(Integer.parseInt(carId));
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object object) {
		if (object == null) {
            return null;
        }
        if (object instanceof Car) {
            Car o = (Car) object;
            return ""+ o.getCarId();
        } else {
            throw new IllegalArgumentException("unexpected type: "+object.getClass().getName());
        }

	}
	
}

